package com.akxy.pt.tsdb.influxdb;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.query.FluxRecord;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Mengfly
 */
public class InfluxDbUtil {

    private static InfluxDBClient client;

    public static void init(InfluxDBClient client) {
        InfluxDbUtil.client = client;
    }

    static <M> List<M> query(InfluxDb influxDb, Class<M> clazz) {
        checkConnection();
        String query = influxDb.queryString();
        return client.getQueryApi().query(query, clazz);
    }

    static <M> List<M> query(InfluxDb influxDb, Function<FluxRecord, M> convertFunction) {
        checkConnection();
        String query = influxDb.queryString();

        return client.getQueryApi().query(query).stream()
                .flatMap(fluxTable -> fluxTable.getRecords().stream())
                .map(convertFunction)
                .collect(Collectors.toList());
    }

    private static void checkConnection() {
        if (client == null) {
            throw new IllegalStateException("Influx Client not initial!!");
        }
    }
}
